import bz2
from copy import deepcopy
import StringIO
from xml.dom.minidom import Document,Node,parseString

from action import ActionSet,Action
from pwl import *
from probability import Distribution
from mctsAgent import mctsAgent
from world import *

class mctsWorld(World):
    '''
    Wrapper with useful methods for MCTS/UTC
    '''
    
    def __init__(self, xml=None):
        World.__init__(self, xml)

    def DoMove(self,actions):
        actionlist = {}
        for item in actions:
            actionlist[item['subject']] = ActionSet([item])
        self.step(actionlist)

    def GetMoves(self):
        states = self.state.domain()
        #what do we do with multiple worlds?
        stateVector = states[0]

        actions = []
        turn = self.next(stateVector)
        for name in turn:
            if stateVector.has_key(modelKey(name)):
                model = self.agents[name].index2model(stateVector[modelKey(name)])
                belief = self.agents[name].getBelief(stateVector,model)
            else:
                belief = self.agents[name].getBelief(stateVector,True)
            agentactions = self.agents[name].getActions(stateVector)
            for state in belief.domain():
                agentactions = agentactions & self.agents[name].getActions(state)
            actions += agentactions


        '''
        turn = self.next(stateVector)
        for name in turn:
            belief = self.agents[name].getBelief(stateVector,True) #other models?
            agentActions = self.agents[name].getActions(stateVector)
            for state in belief.domain():
                print 'agent Actions', agentActions
                print 'getActions', self.agents[name].getActions(state)
                agentActions = agentActions & self.agents[name].getActions(state)
                print 'union', agentActions
                print
                print 'actions', actions
                print 
                for item in agentActions:
                    actions.append(item)
                print 'new actions', actions
        '''
        
        return actions

    def GetTurn(self):
        return self.next(self.state.domain()[0]) #multiple worlds?

    def Clone(self):
        cloned = copy.deepcopy(self)
        cloned.dynamics = self.dynamics #deepcopy changes type of dynamics in tree to string (in Freedonia, at least)
        
        return cloned

    
